// @Author: cyl
// @File: withjson.go
// @Time: 2022/06/10 21:41:36
package main

import (
	"encoding/json"
	"fmt"

	"github.com/tidwall/gjson"
)

type DogAnimal struct {
	Name  string `json:"name" db:"name" ini:"name"`
	Age   int    `json:"age,omitempty"`
	Color string `json:"color"`
}

func (d *DogAnimal) eat() {
	fmt.Printf("%s很能吃!\n", d.Name)
}

func StructWithJson() {
	var one = DogAnimal{
		Name:  "阿黄",
		Age:   6,
		Color: "yellow",
	}
	one.eat()

	// 序列化
	oneJson, _ := json.Marshal(one)
	fmt.Printf("oneJson=%s\n", oneJson) // oneJson={"name":"阿黄","age":6,"color":"yellow"}
	jsonName := gjson.Get(string(oneJson), "name")
	fmt.Println("onejson name:", jsonName) // onejson name: 阿黄

	// 反序列化
	str1 := `{"name": "小黑", "age": 8, "color": "black"}`
	var two DogAnimal
	err := json.Unmarshal([]byte(str1), &two)
	if err != nil {
		fmt.Println("Unmarshal Error:", err)
	}
	fmt.Println("two:", two) // two: {小黑 8 black}
}
